package com.hariro.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hariro.bean.Commodity;
import com.hariro.helper.MySQLiteOpenHelper;
import com.hariro.main.UILApplication;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.qianfeng.project.R;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 删除android ScrollView边界阴影方法 方法一： 在xml中添加：android:fadingEdge=”none”
 * 
 * 方法二： 代码中添加：ScrollView.setHorizontalFadingEdgeEnabled(false);
 */

public class CommodityFragment extends Fragment implements OnClickListener {
	protected static final String TAG = "CommodityFragment";
	private String tagId;
	private String termId;
	private TextView tv_titleBack;
	private ScrollView sl_commodityList;
	public LinearLayout first_commodityList;
	public LinearLayout second_commodityList;
	private RequestQueue requestQueue;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	// 刷新结果
	private String freshResult;
	private String freshRecord;

	private LayoutParams layoutParams;
	private int commodityListWidth;
	private int imageViewHeight;
	public int page;

	private ImageView iv_commodityPic;
	private ImageView iv_collect;
	private TextView tv_collect;
	// 等待动画
	// private ObjectAnimator objectAnimator;
	private RotateAnimation waitLoadDataAnimation;
	private ImageView iv_wait;
	private ImageView iv_commodityPicloading;
	private String url;
	private int firstImageIndex;
	public View view;
	private SQLiteDatabase db;
	private List<String> collectionList;
	private Map<String, ImageView> imageLoadTaskMap;
	private boolean isLoadingCommodityMsgJson = true;

	private Handler isBottomHandler = new Handler() {
		private int lastY;
		private ScrollView scrollView;

		public void handleMessage(android.os.Message msg) {
			if (scrollView == null) {
				scrollView = (ScrollView) msg.obj;
			}
			int scrollY = scrollView.getScrollY();
			int scrollViewHeight = scrollView.getHeight();
			if (imageLoadTaskMap.size() == 0 && !isLoadingCommodityMsgJson) {
				if (lastY == scrollY) {// 停止滚动
					if ((scrollY + scrollViewHeight) >= first_commodityList.getHeight()) {
						Toast.makeText(getActivity(), "滚动到底部啦！开始加载下一页----" + (++page), 0).show();
						url = "http://mobileapi.j.cn/?method=listv4&first=0" + "&start=" + firstImageIndex
								+ "&count=10&uid=&imgSize=mid2&longitude=4.9E-324&latitude=4.9E-324&thisTime=1408342034&lastTime=1408341124&freshRecord=YFDxU48%3D%0A&v=2.0&termId="
								+ termId + "&pid=" + tagId + "&tid=&shopId=&net=wifi";
						loadCommodityJson(url);
					}
				} else {
					lastY = scrollView.getScrollY();
					this.sendEmptyMessageDelayed(0, 10);
				}
			} else {
				Toast.makeText(getActivity(), "还有任务没有加载完成: " + imageLoadTaskMap.size(), 0).show();
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		HashMap<String, Object> map = (HashMap<String, Object>) bundle.get("msg");
		tagId = map.get("tagId").toString();
		termId = map.get("termId").toString();
		tv_titleBack = (TextView) map.get("tv_titleBack");
		url = "http://mobileapi.j.cn/?method=listv4&first=0&start=" + firstImageIndex
				+ "&count=10&uid=&imgSize=mid2&longitude=4.9E-324&latitude=4.9E-324&thisTime=1408342034&lastTime=1408341124&freshRecord=YFDxU48%3D%0A&v=2.0&termId="
				+ termId + "&pid=" + tagId + "&tid=&shopId=&net=wifi";
		requestQueue = Volley.newRequestQueue(getActivity());
		imageLoader = UILApplication.imageLoader;
		options = new DisplayImageOptions.Builder()
				// .showStubImage(R.drawable.common_loading_refresh) 加载等待 时显示的图片
				// .showImageForEmptyUri(R.drawable.defaultcovers) 加载数据为空时显示的图片
				// .showImageOnFail(R.drawable.defaultcovers) 加载失败时显示的图片
				.cacheInMemory().cacheOnDisc()
				/**
				 * .displayer(new RoundedBitmapDisplayer(20))
				 **/
				.build();
		db = new MySQLiteOpenHelper(getActivity(), "", null, 1).getConnection();
		collectionList = new ArrayList<String>();
		asyncSelectCollectList();
		imageLoadTaskMap = new HashMap<String, ImageView>();

		WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		commodityListWidth = (display.getWidth() - 18) / 2;
		// Log.i(TAG, "@@----一个瀑布流的宽度: "+commodityListWidth);

	}

	public void asyncSelectCollectList() {
		final String querySql = "select itemId from tb_collect";
		collectionList.clear();
		new Thread() {
			public void run() {
				Cursor cursor = db.rawQuery(querySql, null);
				while (cursor.moveToNext()) {
					collectionList.add(cursor.getString(0));
					// collectionList.add(cursor.getString(cursor.getColumnIndex("itemId")));
				}
			};
		}.start();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_commodity, null);
		sl_commodityList = (ScrollView) view.findViewById(R.id.sl_commodityList);
		sl_commodityList.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_UP:
					Message message = isBottomHandler.obtainMessage();
					message.obj = sl_commodityList;
					isBottomHandler.sendMessage(message);
					break;

				default:
					break;
				}

				return false;
			}
		});
		first_commodityList = (LinearLayout) view.findViewById(R.id.first_commodityList);
		second_commodityList = (LinearLayout) view.findViewById(R.id.second_commdityList);
		iv_wait = (ImageView) view.findViewById(R.id.iv_wait);
		waitLoadDataAnimation = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		waitLoadDataAnimation.setDuration(100);
		waitLoadDataAnimation.setRepeatCount(10000);
		waitLoadDataAnimation.setRepeatMode(Animation.RESTART);
		iv_wait.startAnimation(waitLoadDataAnimation);
		/*
		 * objectAnimator = ObjectAnimator.ofFloat(iv_wait, "rotation",
		 * 0.0f,90.0f,180.0f,360.0f); objectAnimator.setDuration(200);
		 * objectAnimator.setRepeatCount(1000); objectAnimator.start();
		 */
		loadCommodityJson(url);
		return view;
	}

	public void loadCommodityJson(String url) {
		Log.i(TAG, "@@url：" + url);
		isLoadingCommodityMsgJson = true;
		StringRequest stringRequest = new StringRequest(url, new Listener<String>() {

			@Override
			public void onResponse(String response) {

				isLoadingCommodityMsgJson = false;
				firstImageIndex += 10;
				// 取消动画和隐藏等待的图片
				// 必须清除控件的动画效果才能把其隐藏
				iv_wait.clearAnimation();
				iv_wait.setVisibility(View.GONE);
				waitLoadDataAnimation.cancel();
				// 添加图片到瀑布流列里面
				if (response != null && !"".equals(response)) {
					List<Commodity> list = parsecommodityJson(response);
					if (list != null && list.size() > 0) {
						addCommodityToWall(list);
					} else {
						Toast.makeText(getActivity(), "解析json商品信息出错", Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getActivity(), "没有加载到商品信息的json", Toast.LENGTH_SHORT).show();
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.i(TAG, "@@respone=" + error.getCause());
				Toast.makeText(getActivity(), "商品的数据加载失败,请检查你的网络设置", Toast.LENGTH_SHORT).show();
				isLoadingCommodityMsgJson = false;
			}
		});
		requestQueue.add(stringRequest);
	}

	// 把商品的信息贴到瀑布流中
	protected void addCommodityToWall(List<Commodity> list) {
		for (int i = 0; i < list.size(); i++) {
			Commodity commodity = list.get(i);
			int picWidth = commodity.getPicWidth();
			int picHeight = commodity.getPicHeight();
			/*
			 * Log.i(TAG,"@@picWidth: "+picWidth); Log.i(TAG,"@@picHeight "
			 * +picHeight);
			 */
			if (picWidth > commodityListWidth) {
				float scaleSize = picWidth / (commodityListWidth * 1.0f);
				// Log.i(TAG, "@@图片的缩放比例："+scaleSize);
				imageViewHeight = (int) (picHeight / scaleSize);
			} else {
				imageViewHeight = commodity.getPicHeight();
			}
			// Log.i(TAG, "@@ImageView的高度："+imageViewHeight);
			View view = View.inflate(getActivity(), R.layout.commodity_item, null);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(layoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.setMargins(0, 0, 0, 5);
			view.setLayoutParams(params);
			// 商品图片
			iv_commodityPic = (ImageView) view.findViewById(R.id.iv_commodityPic);
			iv_commodityPic.setLayoutParams(new RelativeLayout.LayoutParams(commodityListWidth, imageViewHeight));
			iv_commodityPic.setScaleType(ScaleType.FIT_XY);
			// 正在加载
			iv_commodityPicloading = (ImageView) view.findViewById(R.id.iv_commodityPicloading);
			waitLoadDataAnimation = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			waitLoadDataAnimation.setDuration(100);
			waitLoadDataAnimation.setRepeatCount(10000);
			waitLoadDataAnimation.setRepeatMode(Animation.RESTART);
			iv_commodityPicloading.startAnimation(waitLoadDataAnimation);
			iv_commodityPicloading.setTag(waitLoadDataAnimation);
			imageLoadTaskMap.put(commodity.getUrl(), iv_commodityPicloading);

			// 网络加载图片
			loadCommodityPic(iv_commodityPic, commodity.getUrl());
			iv_commodityPic.setTag(commodity.getItemId());
			// 商品价格
			TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
			tv_price.setText("￥" + commodity.getPrice());
			// 商品的收藏
			LinearLayout ll_collect = (LinearLayout) view.findViewById(R.id.ll_collect);
			iv_collect = (ImageView) view.findViewById(R.id.iv_collect);
			tv_collect = (TextView) view.findViewById(R.id.tv_collect);
			// 判断该商品的item是否存在收藏列表中
			if (collectionList.contains(commodity.getItemId())) {
				tv_collect.setText("取消收藏");
				iv_collect.setImageResource(R.drawable.common_collection_icon_down);
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("itemId", commodity.getItemId());
			map.put("typeId", commodity.getTypeId() + "");
			ll_collect.setTag(map);
			ll_collect.setOnClickListener(this);
			iv_commodityPic.setOnClickListener(this);
			switch (i % 2) {
			case 0:// 添加到瀑布流的第一列上
				first_commodityList.addView(view);
				break;
			case 1:// 添加到瀑布流的第二列上
				second_commodityList.addView(view);
				break;

			}
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ll_collect:// 收藏
			collectCommodity(view);
			break;
		case R.id.iv_commodityPic:// 商品的详细信息
			commodityMsg(view.getTag().toString());
			break;
		}
	}

	// 商品的详细信息
	public void commodityMsg(String itemId) {
		view.setVisibility(View.GONE);
		tv_titleBack.setText("< 宝贝详情");
		NewShopFragment shopFragment = new NewShopFragment();
		Bundle bundle = new Bundle();
		bundle.putString("itemId", itemId);
		shopFragment.setArguments(bundle);
		FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		fragmentTransaction.replace(R.id.linearLayout_commodityMsgContainer, shopFragment, "ShopFragment");
		fragmentTransaction.commit();
	}

	// 商品收藏功能
	public void collectCommodity(View view) {
		iv_collect = (ImageView) view.findViewById(R.id.iv_collect);
		tv_collect = (TextView) view.findViewById(R.id.tv_collect);
		Map<String, String> map = (Map<String, String>) view.getTag();
		String itemId = map.get("itemId");
		String typeId = map.get("typeId");
		if (tv_collect.getText().toString().equals("收藏")) {
			iv_collect.setImageResource(R.drawable.common_collection_icon_down);
			tv_collect.setText("取消收藏");

			// 查询表中是否包含该收藏项
			String querySql = "select itemId,typeId from tb_collect where itemId=" + itemId;
			Cursor cursor = db.rawQuery(querySql, null);
			if (cursor.getCount() == 0) {
				// 收藏插入的sql语句
				String insertSql = "insert into tb_collect(itemId,typeId) values(" + itemId + "," + typeId + ")";
				db.execSQL(insertSql);
				Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getActivity(), "该商品已经收藏过", 0).show();
			}
		} else {
			Toast.makeText(getActivity(), "取消收藏成功", Toast.LENGTH_SHORT).show();
			iv_collect.setImageResource(R.drawable.common_collection_icon_up);
			tv_collect.setText("收藏");
			// 取消删除字段的操作
			String deleteSql = "delete from tb_collect where itemId=" + itemId;
			db.execSQL(deleteSql);
		}
	}

	// 网络获取商品的图片
	public void loadCommodityPic(ImageView imageView, String url) {
		imageLoader.displayImage(url, imageView, options, new ImageLoadingListener() {
			@Override
			public void onLoadingStarted(String imageUri, View view) {

			}

			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				changeImageViewVisible(imageUri);
			}

			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				changeImageViewVisible(imageUri);
				/*
				 * Log.i(TAG, "@@imageView的宽度：" + iv_commodityPic.getWidth() +
				 * ",imageView的高度：" + iv_commodityPic.getHeight()); Log.i(TAG,
				 * "@@width=" + loadedImage.getWidth() + ",height=" +
				 * loadedImage.getHeight() + "::" + imageUri);
				 */
			}

			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				changeImageViewVisible(imageUri);
			}

			public void changeImageViewVisible(String imageUri) {
				ImageView imageView = imageLoadTaskMap.get(imageUri);
				if (imageView != null) {
					imageView.setVisibility(View.GONE);
					imageView.clearAnimation();
					Animation animation = (Animation) imageView.getTag();
					imageLoadTaskMap.remove(imageUri);
				}
			}
		});
	}

	// 解析上商品信息为List集合
	public List<Commodity> parsecommodityJson(String response) {
		List<Commodity> list = new ArrayList<Commodity>();
		try {
			JSONObject jsonObject = new JSONObject(response);
			freshResult = jsonObject.getString("freshResult");
			freshRecord = jsonObject.getString("freshRecord");
			JSONArray jsonArray = jsonObject.getJSONArray("itemList");
			for (int i = 0; i < jsonArray.length(); i++) {
				String json = jsonArray.get(i).toString();
				Commodity commodity = JSON.parseObject(json, Commodity.class);
				list.add(commodity);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return list;
	}
}
